package org.concepts.java.core.concurrency.executor;

import org.concepts.java.utils.DataUtils;

/**
 * Sorts the list of integer using bubble sort algorithm <a
 * href="http://en.wikipedia.org/wiki/Bubble_sort"
 * >http://en.wikipedia.org/wiki/Bubble_sort</a>.
 * <p/>
 * <iframe width="100%" height="600px"
 * src="http://en.wikipedia.org/wiki/Bubble_sort"/>
 * 
 * 
 * @author vvvv
 * 
 */
public class BubbleSort implements Sorter {

  /**
   * Sort using bubble sort. The passed in input is directly sorted.
   * 
   */
  @Override
  public int[] sort(int[] input) {

    if (input == null || input.length == 1) {
      return input;
    }

    while (swap(input))
      ;

    return input;
  }

  /**
   * Starting from 0 it matches a pair and swaps them if the one on the right is
   * greater than one on the left. true is returned if even a single swap is
   * done
   * 
   * @param input
   *          cannot be null.
   * @return true if a single swap was performed
   */
  private boolean swap(int[] input) {
    boolean swapped = false;

    for (int ctr = 0; ctr + 1 < input.length; ctr++) {
      if (input[ctr] > input[ctr + 1]) {

        int temp = input[ctr];
        input[ctr] = input[ctr + 1];
        input[ctr + 1] = temp;

        swapped = true;
      }
    }
    return swapped;
  }

  /**
   * Quick test to verify that this algorithm is working fine.
   * 
   * @param args
   */
  public static void main(String[] args) {
    int[] numbers = { 3, 2 };
    DataUtils.printArray(numbers);
    DataUtils.printArray(new BubbleSort().sort(numbers));

    int[] numbers1 = { 4, 2, 89, 345, 2432, 466, 234234, 6765, 2343, 4, 2344 };
    DataUtils.printArray(numbers1);
    DataUtils.printArray(new BubbleSort().sort(numbers1));
  }

}
